<?php

class Application_Model_StoreItem extends Application_Model_DomainObject {

    protected $_id; //序号
    protected $_productName; //商品名称
    protected $_orderItemId; //
    protected $_orderId; //订单号
    protected $_orderNo; //订单号
    protected $_price; //商品价格
    protected $_storeId; //仓库ID
    protected $_dateInStore; //入库时间
    protected $_dateOut; //出库时间
	protected $_dateOver;//过期时间
    protected $_operatedate;//操作时间
    protected $_quantity; //数量
    protected $_productId; //产品ID
    protected $_intype; //类型
    protected $_state; //状态 0:未入库 1:已入库 2:已出库
    protected $_operate;//操作状态
    protected $_logisticsName; //物流公司
    protected $_logistics; //物流号
    protected $_userid;
    protected $_image; //图片
    protected $_weight; //重量
    protected $_product; //产品信息
    protected $_remark; //备注
    protected $_createdate; //记录创建时间
    protected $_wayId; //运单序号
    protected $_isPack; //是否有包装
    //12月4号新增
    protected $_bignessType; //体积重量类型
    protected $_isBrand; //是否仿牌
    protected $_isSpecific; //是否特殊的
    protected $_length; //长
    protected $_width; //宽
    protected $_height; //高
    protected $_volumeWeight; //体积重量
    protected $_canVacuum; //能否真空处理
    protected $_vacuumWeight; //真空处理后体积重量
    protected $_noPackageWeight; //去包将后重量
    protected $_isEmbargo; //是否禁运品
    protected $_itemType; //产品类型
    protected $_barcode; //条形码
    protected $_isSelected; //是否被选中
    protected $_cnShipFee; //国家运费
    protected $_remarkName; //用户备注商品名称
    protected $_isdelete; //删除判断
    protected $_embargoReason;
    protected $_locationNo;
    protected $_operateName;
    protected $_interior;
    protected $_isProblem;
    //protected $_storeLocation;

    /**
     * 正常 
     */

    const TYPE_Normal = 0;

    /**
     * 一线仿牌
     */
    const TYPE_Brand = 1;
    /**
     * 配套电池
     */
    const TYPE_Battery = 2; //
    /**
     * 液体
     */
    const TYPE_Liquid = 4; //
    /**
     * 食品
     */
    const TYPE_Food = 8; //
    /**
     * 粉末
     */
    const TYPE_Powder = 16; //

    /**
     * 膏状物 
     */
    const TYPE_Paste = 32;

    /**
     * 药物 
     */
    const TYPE_Drug = 64;

    /**
     * 敏感物品 
     */
    const TYPE_Sensitive = 128;

    /**
     * 纯电池 
     */
    const TYPE_Purebattery = 256;

    /**
     * 保健品 
     */
    const TYPE_Healthcare = 512;

    /**
     * 眼镜 
     */
    const TYPE_Glasses = 1024;

    /**
     * 光盘 
     */
    const TYPE_Cd = 2048;

    /**
     * 化妆品
     */
    const TYPE_Cosmetic = 4096;
    /**
     * 易碎品
     */
    const TYPE_Fragile = 8192;
    /**
     * 二线品牌
     */
    const Type_Two_Brand = 16384;
    /**
     * 移动电源
     */
    const Type_Portable_Battery = 32768;
    /**
     * 电机/马达
     */
    const TYPE_Electrical_Machine = 65536;
    /**
     * 100ml液体
     */
    const TYPE_Liquid_100 = 131072;
    /**
     * 200ml液体
     */
    const TYPE_Liquid_200 = 262144;
    /**
     * 一线品牌
     */
    const TYPE_One_Brand = 524288;
    /**
     * 书籍
     */
    const TYPE_Book = 1048576;


    //前台状态-start
    /**
     * 已入库 
     */
    const STATUS_InStored = 1;

    /**
     * 已出库 
     */
    const STATUS_Sended = 2;
    /**
     * 退货中
     */
    const STATUS_ReturnOf = 4;
    /**
     * 已经退货
     */
    const STATUS_AchieveRe = 5;
    /**
     * 换货中
     */
    const STATUS_Exchange = 6;
    /**
     * 已经换货
     */
    const STATUS_AchieveExchange = 7;
    /**
     * 绑定
     */
    const STATUS_Bind = 10;
    //前台状态-end
    //后台状态-start
    /**
     * 录单
     */
    const Interior_HoldItem = 0;
    /**
     * 入库
     */
    const Interior_InStored = 1;
    /**
     * 申请出库
     */
    const Interior_ApplyFor = 2;
    /**
     * 已拣货
     */
    const Interior_PickIng = 3;
    /**
     * 已打包
     */
    const Interior_Pack = 4;
    /**
     * 已出库
     */
    const Interior_OutStore = 10;
    /**
     * 扣压中
     */
    const Interior_Withhold = 21;
    /**
     * 退回中
     */
    const Interior_ReturnIng = 22;
    /**
     * 已退回
     */
    const Interior_ReturnStore = 30;
    /**
     * 申请退货
     */
    const Interior_ApplyForAlteration = 41;
    /**
     * 退换货中
     */
    const Interior_AlterationIng = 42;
    /**
     * 已遗失
     */
    const Interior_LoseStore = 50;
    /**
     * 已退货
     */
    const Interior_AchieveReturn = 43;
    /**
     * 已换货
     */
    const Interior_AchieveExchange = 44;
    /**
     * 完成
     */
    const Interior_Achieve = 100;
    /**
     * 申请换货
     */
    const Interior_Exchange = 45;
    /**
     * 销毁
     */
    const Interior_Destroy = -1;
    //后台状态-end

    //操作记录statr
    /**
     * 过期出库
     */
    const Operate_past = 1;
     /**
     *后台丢弃
     */
    const Operate_admin = 1;
     /**
     *用户丢弃
     */
    const Operate_user = 2;
    //操作记录end

    /**
     * 自助包裹
     */
    const SOURCE_SELF = 0;

    /**
     * 代购
     */
    const SOURCE_AGENT_BUY = 1;

    /**
     * 上门取货包裹
     */
    const SOURCE_VISITING = 2;
    /**
     * 上门取件直发海外
     */
    const SOURCE_VISITINGWAY = 3;
    /**
     * 中国深圳仓库
     */
    const Location_China = 1;
    /**
     * 美国加州仓库
     */
    const Location_CA = 2;
    /**
     * 会员卡条码
     */
    const User_Barcode = "gift";

    public static function getStatusNames() {
        return array(
            self::STATUS_InStored => "已入库"
            , self::STATUS_Sended => "已出库"
            , self::STATUS_ReturnOf => "退货中"
            , self::STATUS_AchieveRe => '完成退货'
            , self::STATUS_Exchange => '换货中'
            , self::STATUS_AchieveExchange => '完成换货'
            , self::STATUS_Bind => "已绑定"
        );
    }

    public function getStatusName() {
        $arrStatusNames = self::getStatusNames();
        return $arrStatusNames[$this->_state];
    }

    public static function getInteriorNames() {
        return array(
            self::Interior_HoldItem => "已录单"
            , self::Interior_InStored => "已入库"
            , self::Interior_ApplyFor => "申请出库"
            , self::Interior_PickIng => "已拣货"
            , self::Interior_Pack => "已打包"
            , self::Interior_OutStore => "已出库"
            , self::Interior_Withhold => "扣压中"
            , self::Interior_ReturnIng => "退回中"
            , self::Interior_ReturnStore => "已退回"
            , self::Interior_ApplyForAlteration => "申请退货"
            , self::Interior_AlterationIng => "退换货中"
            , self::Interior_AchieveReturn => "已退货"
            , self::Interior_AchieveExchange => "已换货"
            , self::Interior_LoseStore => "已遗失"
            , self::Interior_Achieve => "完成出库"
            , self::Interior_Destroy => "已销毁"
            , self::Interior_Exchange => "申请换货"
        );
    }

    public function getInteriorName() {
        $arrInteriorNames = self::getInteriorNames();
        if ($this->_interior != null) {
            return $arrInteriorNames[$this->_interior];
        } else {
            return "无状态";
        }
    }

    public static function interiorNameByNum($num) {
        switch ($num) {
            case self::Interior_HoldItem:
                return "已录单";
                break;
            case self::Interior_InStored:
                return "已入库";
                break;
            case self::Interior_ApplyFor:
                return "申请出库";
                break;
            case self::Interior_PickIng:
                return "已拣货";
                break;
            case self::Interior_Pack:
                return "已打包";
                break;
            case self::Interior_OutStore:
                return "已出库";
                break;
            case self::Interior_Withhold:
                return "扣压中";
                break;
            case self::Interior_ReturnIng:
                return "退回中";
                break;
            case self::Interior_ReturnStore:
                return "已退回";
                break;
            case self::Interior_ApplyForAlteration:
                return "申请退货";
                break;
            case self::Interior_AlterationIng:
                return "退换货中";
                break;
            case self::Interior_AchieveReturn:
                return "已退货";
                break;
            case self::Interior_AchieveExchange:
                return "已换货";
                break;
            case self::Interior_LoseStore:
                return "已遗失";
                break;
            case self::Interior_Achieve:
                return "完成出库";
                break;
            case self::Interior_Destroy:
                return "已销毁";
                break;
            case self::Interior_Exchange:
                return "申请换货";
        }
    }

    public static function getNames() {
        return array(
            self::TYPE_Normal=> array('正常', '', '')
            // , self::TYPE_Brand => array('品牌', 'tz5', '仿牌是指仿冒名牌或没有正规发票的名牌产品。UPS和Fedex不接收仿牌，DHL牌子货通道，EMS、邮政小包可正常出货。')
            , self::TYPE_One_Brand => array('一线品牌', 'tz5', '是指仿冒国际知名的一线品牌或没有正规发票的产品。UPS，联邦以及DHL不接受一线品牌；EMS，邮政小包可正常出货。')
            , self::Type_Two_Brand => array('二线品牌', 'tz5', '是指仿冒国内知名品牌或没有正规发票的产品。UPS，联邦不接受二线品牌，其余渠道可正常出货。')
            , self::TYPE_Purebattery => array('纯电池', 'tz4', '指锂电池，蓄电池，镍铬电池，全氢电池等。四大快递均不接受纯电池，邮政类渠道可出货，不过有被查扣的风险。')
            , self::TYPE_Battery => array('配套电池', 'tz4', '是指不含发动机或马达在内的家用电器，手机，电脑等电子产品。功率在100WH以下可走四大快递，邮政类渠道不建议出货。')
            , self::Type_Portable_Battery => array('移动电源', 'tz4', '是指集供电和充电功能于一体的便携式充电器，一般由锂电芯或者干电池作为储电单元。UPS，香港EMS特殊可正常出货，其余渠道不建议出货。')
            , self::TYPE_Electrical_Machine => array('电机/马达', 'tz4', '分为直流电机和交流电机，功率100W以下的电机，可与机器一起出货(四大快递)，无法单独出货。100W以上电机/马达，暂时无渠道可走。')
            , self::TYPE_Food => array('食品', 'tz3', '美国不能发送食品，其他可正常发货。')
            , self::TYPE_Powder => array('粉末', 'tz4', '敏感物品，只有EMS,邮政小包可接收少量粉末，且必须与别的物品混合配送。')
            , self::TYPE_Paste => array('膏状', 'tz3', '敏感物品，只有EMS,邮政小包可接收少量膏状物，且必须与别的物品混合配送。')
            , self::TYPE_Drug => array('处方药', 'tz3', '敏感物品，只有EMS,邮政小包可接收少量药物。')
            , self::TYPE_Sensitive => array('其他敏感', 'tz4', '敏感物品，只有EMS,邮政小包可接收少量敏感物品。')
            , self::TYPE_Healthcare => array('保健品', 'tz4', '敏感物品，只有EMS,邮政小包可接收少量敏感物品。')
            , self::TYPE_Glasses => array('眼镜', 'tz4', '敏感物品，只有EMS,邮政小包可接收少量敏感物品。')
            , self::TYPE_Cd => array('光盘', 'tz4', '敏感物品，只有EMS,邮政小包可接收少量敏感物品。')
            , self::TYPE_Cosmetic => array('化妆品', 'tz3', '敏感物品，只有EMS,邮政小包可接收少量液体，且必须与别的物品混合配送。')
            , self::TYPE_Fragile => array('易碎', '', '易碎品')
            , self::TYPE_Liquid => array('50ml以下液体', 'tz3', '是指纯液体或含液体在内的敏感物品，50ml以下液体，可与其他物品一起出运，无法单独出运，邮政类渠道正常出货。')
            , self::TYPE_Liquid_100 => array('100ml以下液体', 'tz3', '是指纯液体或含液体在内的敏感物品，100ml液体可冲货。')
            , self::TYPE_Liquid_200 => array('100ml以上液体', 'tz3', '是指纯液体或含液体在内的敏感物品，200ml以上液体，香港EMS特殊可出货，其他渠道无法出运。')
            , self::TYPE_Book => array('书籍','tz3', '部分快递针对书籍有了限制，包裹内含有书籍的货物无法出运。')
        );
    }

    public static function getTypeNames()
    {
        return array('1' => array("name"=>"创意卡包一个","img"=>"/data/2013-09/f964daa46140ee1a495dc5fba5887a9e.jpg")
            , "2" => array("name"=>"创意手机支架一个","img"=>"/data/2013-09/ed1e1a5c7e3a5fa544e37802364c722c.jpg")
            , "3" => array("name"=>"兔兔玩偶挂件一个","img"=>"/data/2013-09/cfb5b430a12bbbdb6dca67123a3e22f0.jpg")
            , "4" => array("name"=>"创意书签一个","img"=>"/data/2013-09/97c588ff387276e29d148966372b0313.jpg")
            , "5" => array("name"=>"创意生活骰子一个","img"=>"/data/2013-09/97ffbddab13c071425700684bbe108d2.jpg")
            , "6" => array("name"=>"袖珍绝望鸡一个","img"=>"/data/2013-09/4c88aa85ae26c096aaa7bf284066a1d0.jpg")
        );
    }

    public static function getStoreLocationAll() {
        return array(
            self::Location_China => "中国深圳"
            , self::Location_CA => "美国加州"
        );
    }

    public function getStoreLocationName() {
        $arrStoreLocation = self::getStoreLocationAll();
        return $arrStoreLocation[$this->_storeLocation];
    }


    public function getItemTypeName() {
        $names = self::getNames();
        if ($this->_itemType == 0) {
            return $names['0'][0];
        }
        $nameAll = '';
        if ($this->_itemType) {
            foreach ($names as $key => $name) {
                if ($key != 0 && ($this->ItemType & $key) == $key) {
                    $nameAll = $nameAll . $name[0] . '/';
                }
            }
        }
        return $nameAll;
    }

    /**
     * 返回数据持久化对象
     * @return Application_Model_StoreItem
     */
    protected static function getDb() {
        return new Application_Model_DbTable_StoreItem();
    }

    public function getimageFile() {

        if ($this->_image == null || $this->_image == '') {
            return Application_Model_Product::DEFAULT_IMAGE;
        } else {
            return $this->_image;
        }
    }

    /*
     * 新增仓库单
     */

    public function addItem(Application_Model_StoreItem $newItem) {
        $newItem->save();
    }

    /**
     * 根据userid返回一个仓库货物数组
     * @param int $userid
     * @return array
     */
    public static function getByuserId($userid, $state, $start, $row) {


        //$result=Application_Model_StoreItem::getDb()->queryAll(array('userid'=>$userid));//方案一            
        $result = self::getDb()->getByUser($userid, $state, $start, $row); //方案二

        foreach ($result as $item) {
            if ($item->productId != null) {
                $item->product = new Application_Model_Product($item->productId);
            }
        }
        return $result;
    }
    
    public static function getCountByUserId($userId)
    {
        return self::getDao()->count(array("userid = "=>  $userId,"  and (isdelete is null or isdelete = 0) and barcode != "=> self::User_Barcode));
    }

    /**
     * 根据id列表获取仓库信息
     * @param type $ids id列表,如：1,2,3
     * @return type  仓库数组
     */
    public static function getByids($ids) {
        $result = self::getDb()->getByids($ids);
        return $result;
    }

    /*
     * 根据用户名，状态获取当前仓库记录总数
     * @param int $userid 用户序号
     * @param int $state 用户序号
     * @return int
     */

    public static function getItemCount($userid, $state) {
        $where = array('userId' => $userid, ' and isdelete != ' => 1);
        if ($state != NULL) {
            $where['state'] = $state;
        }
        return self::getDao()->count($where);
    }


    public static function getItemCountbylno($userid, $location) {
        $where = array('userId' => $userid, ' and isdelete != ' => 1);
        if ($location != NULL) {
            $where['locationNo'] = $location;
        }
        return self::getDao()->count($where);
    }


    public static function getInTypeCount($userid, $state) {

        $store = new Application_Model_DbTable_StoreItem();

        return $store->getInTypeCount($userid, $state);
    }

    public static function getBywayId($wayid) {
        $store = new Application_Model_DbTable_StoreItem();

        return $store->getBywayId($wayid);
    }

    /**
     * 根据指定的条件返回
     * @param int $wayid
     * @param int $memberId
     * @param date $startTime 开始时间
     * @param date $endTime 结束时间
     * @param int $status 订单状态
     * @param int $count
     * @param int $offset
     * @return 返回格式为 array('size'=>?,'list'=>?,'pages'=>?,'index'=>?) 
     * size为查询记录的总条数，list为返回的array型数据，pages是指有多少页，index为当前是哪一页 
     */
    public static function getByFilter($wayid, $memberId, $startTime, $endTime, $status, $count, $offset, $isdelete = 0) {
        $where = array('isdelete' => 0);
        $and = ' and ';
        if ($wayid != NULL) {
            $where['  Id = '] = $wayid;
            $and = ' and ';
        }

        if ($memberId != NULL) {
            $where[$and . ' userId = '] = $memberId;
            $and = ' and ';
        }

        if ($startTime != NULL) {
            $where[$and . ' dateInStore >= '] = $startTime;
            $and = ' and ';
        }

        if ($endTime != NULL) {
            $where[$and . ' dateInStore <= '] = $endTime;
            $and = ' and ';
        }

        if ($status != NULL) {
            $where[$and . ' state = '] = $status;
            $and = ' and ';
        }
//        var_dump($where);
        return self::getDb()->queryPage($where, 'id desc ', $count, $offset);
    }

    /**
     * 
     * @param type $memberId
     * @param type $count
     * @param type $offset
     * @return type
     */
    public static function getMyStore($memberId, $count, $offset) {
        return self::getByFilter(NULL, $memberId, NULL, NULL, 1, $count, $offset);
    }

    /**
     * 是否是禁止选择的选项
     * @return type 
     */
    public function isDisabled() {
        return $this->_state != self::STATUS_InStored || $this->_isEmbargo;
    }

    /**
     * 是否已经选中
     * @return type 
     */
    public function isSelect() {
        return $this->_isSelected && !$this->isDisabled();
    }

    /**
     * 返回所有已经选中仓库项
     * @param type $userid
     * @return type 
     */
    public static function getMySelect($userid) {
        return self::getDb()->queryAll(array('userid' => $userid, 'isSelected' => 1, 'state' => self::STATUS_InStored,'isdelete' =>0));
    }

    /**
     * 返回体积重量
     * @param type $array
     * @return type 
     */
    public static function getSumVolumeWeight($array) {
        $weight = 0;
        foreach ($array as $item) {
            if ($item->VolumeWeight) {
                $weight += $item->VolumeWeight;
            } else {
                $weight += $item->Weight;
            }
        }
        return $weight;
    }

    /**
     * 返加总重量
     * @param type $array 
     */
    public static function getSumWeight($array) {
        $weight = 0;
        foreach ($array as $key) {
            $weight += $key->weight;
        }
        return $weight;
    }

    /**
     * 获取今日入库的包裹数量
     */
    public static function getcountinstore($stime = null, $etime = null) {
        if ($stime != null) {
            $where[' dateInStore >='] = $stime;
        } else {
            $where[' dateInStore >='] = date('Y-m-d');
        }
        if ($etime != null) {
            $where[' and dateInStore <='] = $etime . " 23:59:59";
        }
        return self::getDao()->count($where);
    }

    /**
     * 获取今日出库的包裹数量
     */
    public static function getcountoutstore($stime = null, $etime = null) {
        if ($stime != null) {
            $where[' dateOut >='] = $stime;
        } else {
            $where[' dateOut >='] = date('Y-m-d');
        }
        if ($etime != null) {
            $where[' and dateOut <='] = $etime . " 23:59:59";
        }
        $where[' and state = '] = self::STATUS_Sended;
        return self::getDao()->count($where);
    }

    public static function getInStoreWeight($stime = null, $etime = null) {
        if ($stime != null) {
            $where[' dateInStore >='] = $stime;
        } else {
            $where[' dateInStore >='] = date('Y-m-d');
        }
        if ($etime != null) {
            $where[' and dateInStore <='] = $etime . " 23:59:59";
        }
        $storeItem = self::getDao()->queryAll($where);
        $sumWeight = 0;
        if ($storeItem) {
            foreach ($storeItem as $storeVal) {
                $sumWeight += $storeVal->weight;
            }
        }
        return $sumWeight;
    }

    public static function countstore($status) {
        if ($status != '') {
            if ($status == 1) {
                $where[' dateInStore >'] = date('Y-m-d');
                $and = " and ";
            } else {
                $where[' dateOut >'] = date('Y-m-d');
                $and = " and ";
            }
            $where[$and . ' (isdelete is null or isdelete = 0) and '] = 1;
            //$where['and  state = '] =  $status;
            return self::getDao()->count($where);
        } else {
            return 0;
        }
    }

    /* 根据用户ID 返回用户历史包裹的个数 */

    public static function personalCount($userid) {
        $where = array();
        $where['userid = '] = $userid;
        $where[' and interior > 1 and (isdelete = 0 or isdelete is null) and '] = 1;
        return self::getDb()->count($where);
    }

    /* 根据用户ID 返回用户现有库存包裹的个数 */

    public static function personalInCount($userid) {
        $where = array();
        $where['userid = '] = $userid;
        $where[' and (interior = '] = self::Interior_InStored;
        $where[' or interior = '] = self::Interior_HoldItem;
        $where[') and (isdelete = 0 or isdelete is null) and '] = 1;
        return self::getDb()->count($where);
    }

    public static function countnotscan($beyond = null) {
        $time = date("Y-m-d H:i:s",time()-3600*36);
        $where = array();
        $where['(interior= '] = self::Interior_HoldItem;
        $where[' or interior= '] = self::Interior_InStored;
        if($beyond == "beyond"){
            $where[") and dateInStore < '".$time."' and (locationNo is null) and (isdelete is null or isdelete = 0) and "] = 1;
        }else{
            $where[') and locationNo is null and (isdelete is null or isdelete = 0) and '] = 1;
        }
        return self::getDao()->count($where);
    }

    public static function coustore($userid) {
        $where[' userid = '] = $userid;
        $where[' and ( interior = '] = self::Interior_HoldItem;
        $where[' or interior = '] = self::Interior_InStored;
        $where[') and (isdelete is null or isdelete = 0) and '] = 1;
        return self::getDao()->count($where);
    }

    /**
     * 根据userid，加载user对象
     * @author wuzw
     * @return type
     */
    public function getuserinfo() {
        if ($this->_userid) {
            return Application_Model_User::load($this->_userid);
        }
    }

    public static function getMyByFilter($storeItemSearch, $pagesize, $start) {
//        var_dump($storeItemSearch->getSearchFileds());exit;
        return self::getDao()->queryPage($storeItemSearch->getSearchFileds(), " id desc ", $pagesize, $start);
    }

    //删除和过期物品列表
    public static function getMydeleteByFilter($storeItemSearch, $pagesize, $start) {
        return self::getDao()->queryPage($storeItemSearch->getdelleteSearchFileds(), " id desc ", $pagesize, $start);
    }

    //历史库存
    public static function getHistoryFilter($storeItemSearch, $pagesize, $start){
        return self::getDao()->queryPage($storeItemSearch->getHistoryFilter(), " id desc ", $pagesize, $start);
    }

    //打印丢弃和过期物品
    public static function getPrintdeletelist($id){
        $id = "(" . $id . "0)";
        $where[" id in "] = $id;
        return self::getDao()->queryAll($where," id desc ");
    }
    //扫描物品，判断是否过期或丢弃
    public static function getcheckbarcode($barcode){
        $time = date('Y-m-d', strtotime('- ' . 7 . ' month'));
        $where[" barcode = "] = $barcode;
        $where[" and state = "] = 1;
        $where[" and (isdelete = "] = 1;
        $where[" or dateInStore <  "] = $time;
        $where[') and '] = 1;
        $result = self::getDao()->queryOne($where);
        if($result==NULL || empty($result) ){
            return 2;
        }elseif($result && ($result->isdelete==1 || $result->dateInStore < $time )){
            if($result->isdelete!=1){
                 $result->operate=self::Operate_past;
            }
            $result->locationNo=NULL;
            $result->dateOut=date('Y-m-d H:i:s');
            $result->state=2;
            $result->interior=self::Interior_OutStore;
            $result->save();
            return 1;
        }

    }


     //批量出库，判断是否过期或丢弃
    public static function getcheckbath($idlist){
        //var_dump($idlist);die;
        $time = date('Y-m-d', strtotime('- ' . 7 . ' month'));
        $idlist = "(" . $idlist . "0)";
        $where[" id in "] = $idlist;
        $where[" and state = "] = 1;
        $where[" and (isdelete = "] = 1;
        $where[" or dateInStore <  "] = $time;
        $where[') and '] = 1;
        $result = self::getDao()->queryAll($where);
        foreach($result as $item){
            if($item==NULL || empty($item) ){
                return 2;
            }elseif($item->locationNo!=NULL){
                return 3;
            }elseif($item && ($item->isdelete==1 || $item->dateInStore < $time )){
                    if($item->isdelete!=1){
                         $item->operate=self::Operate_past;
                    }
                    $item->locationNo=NULL;
                    $item->dateOut=date('Y-m-d H:i:s');
                    $item->state=2;
                    $item->interior=self::Interior_OutStore;
                    $item->save();
                    
            }
        }
            return 1;
    }

    public static function bybarcode($barcode) {
        $where[" barcode like "] = "%" . $barcode . "%";
        return self::getDao()->queryOne($where);
    }

    public static function surebybarcode($barcode) {
        $where[" barcode = "] = $barcode;
        return self::getDao()->queryOne($where);
    }

    /*
     * 根据用户id获取用户仓库号
     */

    public function getbystoreno() {
        $userid = $this->_userid;
        return Application_Model_User::load($userid);
    }

    public function delstore($idlist) {
        $arrid = explode(",", $idlist);
        foreach ($arrid as $key => $value) {
            if ($value != '') {
                $where['id = '] = $value;
                $result = self::getDao()->queryOne($where);
                $result->state = self::STATUS_Sended;
                $result->isdelete = 1;
                $result->save();
                Application_Model_Operate::addOperate(0, null, $result->Logistics, "删除包裹 " . $result->Logistics, $result->userid);
            }
        }
        return true;
    }

    public static function getstoreuser($idlist) {
        $arrid = explode(",", $idlist);
        foreach ($arrid as $value) {
            if ($value != '') {
                $result = self::load($value);

                if ($result->state != self::STATUS_InStored) {
                    return 2;
                }
            }
        }
   
        $id = "(" . $idlist . "0)";
        $where[" id in "] = $id;
        $storeItem = self::getDao()->queryAll($where);
        $arruser = array();
        foreach ($storeItem as $value) {
            $arruser[$value->userid] = 1;
            $userId = $value->userid;
        }
        if (count($arruser) == 1) {
            return array("storeItem"=>$storeItem,"userId"=>$userId);
        } else {
            return 4;
        }
    }

    public static function byselsstore($id, $userid, $count, $offset) {
        $where[" id in "] = "(" . $id . "0)";
        $where[" and userid = "] = $userid;
        $where[" and state = "] = self::STATUS_InStored;
        $where[" and (wayId = "] = "";
        $where[" or wayId is null ) and "] = 1;
        return self::getDao()->queryPage($where, " id desc ", $count, $offset);
    }

    public static function bysurplusstore($id, $userid, $count, $offset) {
        $where[" id not in "] = "(" . $id . "0)";
        $where[" and userid = "] = $userid;
        $where[" and state = "] = self::STATUS_InStored;
        $where[" and (wayId = "] = "";
        $where[" or wayId is null ) and "] = 1;
        return self::getDao()->queryPage($where, " id desc ", $count, $offset);
    }

    
    public function addImg($imgurl,$status) {
        $imgItem = new Application_Model_StoreImg();
        $imgItem->storeid = $this->_id;
        $imgItem->imgurl = $imgurl;
        $imgItem->status = $status;
        $imgItem->dateCreated = date("Y-m-d H:i:s");
        $imgItem->save();
    }
    
    public function getImgs()
    {
        return Application_Model_StoreImg::getImgAllByStoreId($this->_id);
    }

    public function getStoreIdWay() {
        return Application_Model_WayItem::getDao()->queryAll(array("storeItemId" => $this->_id));
    }

    public static function openNewLocation($userid) {
        $weight = 0;
        $where = array();
        $where['(interior= '] = self::Interior_HoldItem;
        $where[' or interior='] = self::Interior_InStored;
        $where[') and userid ='] = $userid;
        $res = self::getDao()->queryAll($where);
        foreach ($res as $val) {
            if ($val->volumeWeight) {
                $weight += $val->volumeWeight;
            } else {
                $weight += $val->weight;
            }
        }
        $quantity = 0;
        foreach ($res as $val) {
            $quantity += $val->quantity;
        }
        $count = Application_Model_StoreLocation::getDao()->count(array('userId' => $userid));
        if ($count <= 1) {
            $count = 1;
        }
        $vweight = ($weight / 1000) / $count;
        $time = date("Y-m-d");
        $opt = Application_Model_User::load($userid);
        $location = Application_Model_StoreLocation::getLocation($userid);
        $inGoodsCount = self::getDao()->count(array('userId' => $userid, 'interior' => Application_Model_StoreItem::Interior_InStored));
        if ($vweight > 20 || $quantity > (15 * $count)) {
            if ($opt->locationtime != $time) {
                return 1;
            }
        } else if (!$location) {
            if ($opt->locationtime != $time) {
                return 1;
            }
        } else if ($inGoodsCount == 0) {
            if ($opt->locationtime != $time) {
                return 1;
            }
        } else {
            return 0;
        }
    }

    public function getwaybillinfo() {
        if ($this->_id) {
            $wayItem = Application_Model_WayItem::getDao()->queryAll(array('storeItemId' => $this->_id), ' id DESC');
            if ($wayItem) {
                return Application_Model_wayBillItem::load($wayItem[0]->wayId);
            } else {
                return "";
            }
        }
    }

    public function isNullLocation($userid) {
        $where = array();
        $where['(interior = '] = self::Interior_HoldItem;
        $where[' or interior = '] = self::Interior_InStored;
        $where[') AND userid = '] = $userid;
        return self::getDao()->count($where);
    }

    public static function countinstore($num) {
        $where = array();
        if ($num == 1) {
            $where['(interior = '] = self::Interior_InStored;
            $where[' or interior = '] = self::Interior_HoldItem;
            $where[') and (isdelete is null or isdelete = 0) and '] = 1;
        }
        return self::getDao()->count($where);
    }

    public static function countSpecialPackage() {
        $where['(locationNo = '] = "GZ-11";
        $where[' or locationNo  = '] = "BH-11";
        $where[' or locationNo = '] = "TS-11";
        $where[' or locationNo   = '] = "GQ-11";
        $where[') and (isdelete is null or isdelete = 0) and '] = 1;
        return self::getDao()->count($where);
    }

    /* public static function getNewBarcode(){
      $barcode = date("ymd") . substr(time(), -5, 5);
      return Application_Model_StoreItem::getDao()->count(array('barcode'=>$barcode))?Application_Model_StoreItem::getNewBarcode():$barcode;
      } */

    public static function isSetBarcode($barcode) {
        return self::getDao()->count(array('barcode' => $barcode));
    }

    public static function manageInboundWeight($num, $username) {
        $where = array();
        if ($num == 1) {
            $mytime = date("Y-m-d", time() - 31 * 24 * 3600);
            $where['dateInStore >= '] = $mytime;
            $where['and operateName = '] = $username;
        } else if ($num == 2) {
            $mytime = date("Y-m", time());
            $where['dateInStore >= '] = $mytime;
        }
        $inboundWeight = self::getDao()->sum($where, 'weight');
        return $inboundWeight / 1000;
    }

    public static function manageOutboundWeight($num, $username) {
        $where = array();
        if ($num == 1) {
            $mytime = date("Y-m-d", time() - 31 * 24 * 3600);
            $where['dateOut >= '] = $mytime;
            $where['and operateName = '] = $username;
        } else if ($num == 2) {
            $mytime = date("Y-m", time());
            $where['dateOut >= '] = $mytime;
        }
        $outboundWeight = self::getDao()->sum($where, 'weight');
        return $outboundWeight / 1000;
    }

    public static function countStoreByday($num, $username, $day) {
        $where = array();
        if ($num == 1) {
            $where['dateInStore like '] = "%" . $day . "%";
            $where[' and operateName = '] = $username;
        } else if ($num == 2) {
            $where['dateOut like '] = "%" . $day . "%";
            $where[' and operateName = '] = $username;
        } else if ($num == 3) {
            $where['dateInStore like '] = "%" . $day . "%";
        } else if ($num == 4) {
            $where['dateOut like '] = "%" . $day . "%";
        }
        return self::getDao()->count($where);
    }

    public static function weightStoreByday($num, $username, $day) {
        $where = array();
        if ($num == 1) {
            $where['dateInStore like '] = "%" . $day . "%";
            $where[' and operateName = '] = $username;
        } else if ($num == 2) {
            $where['dateOut like '] = "%" . $day . "%";
            $where[' and operateName = '] = $username;
        } else if ($num == 3) {
            $where['dateInStore like '] = "%" . $day . "%";
        } else if ($num == 4) {
            $where['dateOut like '] = "%" . $day . "%";
        }
        return self::getDao()->sum($where, 'weight');
    }

    public static function manageInCount($num, $username) {
        $where = array();
        if ($num == 1) {
            $mytime = date("Y-m-d", time() - 31 * 24 * 3600);
            $where['dateInStore >= '] = $mytime;
            $where['and operateName = '] = $username;
        } else if ($num == 2) {
            $mytime = date("Y-m", time());
            $where['dateInStore >= '] = $mytime;
        }
        return self::getDao()->count($where);
    }

    public static function manageOutCount($num, $username) {
        $where = array();
        if ($num == 1) {
            $mytime = date("Y-m-d", time() - 31 * 24 * 3600);
            $where['dateOut >= '] = $mytime;
            $where['and operateName = '] = $username;
        } else if ($num == 2) {
            $mytime = date("Y-m", time());
            $where['dateOut >= '] = $mytime;
        }
        return self::getDao()->count($where);
    }

    public static function getbyLogistics($logistics) {
        $where[" logistics = "] = $logistics;
        return self::getDao()->queryOne($where);
    }

    public static function getAllbyLogistics($logistics) {
        return self::getDao()->queryAll(array("logistics" => $logistics));
    }

    public function getLogisticsShow() {
        if (strpos($this->_logistics, ']') > 0) {
            return $this->_logistics;
        }
        return "[$this->_logisticsName]$this->_logistics";
    }

    /**
     * 返回一个物品唯一条形码
     * @return type
     */
    public static function createBarcode() {
        //return substr((microtime(TRUE) - strtotime('2013-01-01')) * 1000000, 0, 11);
        return substr((microtime(TRUE) - strtotime('2013-01-01')) * 100000, 0, 12);
    }

    public static function countProblem() {
        return self::getDao()->count(array("isProblem" => 1));
    }

    public static function getByUserIdBarcode($userId, $barcode) {
        return self::getDao()->queryOne(array("userId = " => $userId, " and barcode like " => $barcode."%"));
    }

    private $_orderItem = null;

    public function getOrderItem() {
        if ($this->_orderItem == NULL)
            $this->_orderItem = Application_Model_Order::bylogistics($this->_logistics);
        if ($this->_orderItem == NULL)
            $this->_orderItem = Application_Model_Order::load($this->_storeId);
        return $this->_orderItem;
    }
    
    public function getActCnShipFee($logistics){
        $store = new Application_Model_DbTable_StoreItem();
        return $store->getActCnShipFee($logistics);
    }
    
    public function getProblemInfo()
    {
        $item = false;
        if($this->_intype == "预报包裹"){
            $item = Application_Model_ingstore::getByShipNo($this->_logistics);
        } else if ($this->_intype == "代购订单") {
            $item = Application_Model_Order::getByShipNo($this->_logistics);
        } else if ($this->_intype == "上门取件") {
            $item = Application_Model_VisitingServer::getByShipNo($this->_logistics);
        } else if ($this->_intype == "网购包裹"){
            $ingstore = Application_Model_ingstore::getByShipNo($this->_logistics);
            $item = Application_Model_ingstoreproduct::getbyingstoreid($ingstore->id);
        }
        return $item?$item:false;
    }
    
    public static function getFilterAll($storeItemSearch)
    { 
//        var_dump($storeItemSearch->getSearchFileds());exit;
        return Application_Model_StoreItem::getDao()->queryAll($storeItemSearch->getSearchFileds());
    }

    public static function getOne($storeSearch)
    {
//        var_dump($storeSearch->getSearchFileds());exit;
        return Application_Model_StoreItem::getDao()->queryOne($storeSearch->getSearchFileds());
    }
    
    public static function getCount($storeSearch)
    {
        return Application_Model_StoreItem::getDao()->count($storeSearch->getSearchFileds());
    }
    public function getUserType()
    {
        $storeSearch = new Application_Model_Filter_StoreItemSearch();
        $storeSearch->userId = $this->_userid;
        $count = Application_Model_StoreItem::getCount($storeSearch);
        if($count>1){
            return "老用户";
        }
        return "新用户";
    }

    public static function getDaytimeCount($objlist){
          $Auto['sum'] =0;
          $Auto['wsum'] =0;
          $list = array();
          foreach ($objlist as $value) {
                  $date = date("Y-m-d",  strtotime($value->dateInStore));
                  $list[$date]["date"] = $date;
                  $list[$date]["wsum"] = isset($list[$date]["wsum"])?$list[$date]["wsum"]:0;
                  $list[$date]["sum"] = isset($list[$date]["sum"])?$list[$date]["sum"]:0;
                  
                  $list[$date]["wsum"] += $value->weight;
                  $num = ceil($value->weight/5000); 
                  $sum = $num>10?10:$num; 
                  $list[$date]["sum"] +=$sum;
                  
            }
            foreach ($list as  $value) {
                  $Auto['wsum'] += $value["wsum"];
                  $Auto['sum'] += $value["sum"];
            }
//            var_dump($list); 
            if($list && $Auto){
                  return array($list,$Auto);
            }  else {
                  return;
            }
            
    }
    /**
     * 复制一份商品
     * @param type $userId
     */
    public function copyStore($userId) {
        $item = new Application_Model_StoreItem();
        $item->ProductName = $this->_productName;
        $item->StoreId = $this->_storeId;
        $item->DateInStore = date("Y-m-d H:i:s");
        $item->Quantity = 1;
        $item->State = Application_Model_StoreItem::STATUS_InStored;
        $item->LogisticsName = $this->_logisticsName;
        $item->Logistics = $this->_logistics;
        $item->OrderNo = $this->_orderNo;
        $item->Userid = $userId;
        $item->Weight = $this->_weight;
        $item->Createdate = date("Y-m-d H:i:s");
        $item->VolumeWeight = $this->_volumeWeight;
        $item->BignessType = $this->_bignessType;
        $item->IsBrand = $this->_isBrand;
        $item->IsSpecific = $this->_isSpecific;
        $item->CanVacuum = $this->_canVacuum;
        $item->IsEmbargo = $this->_isEmbargo;
        $item->Barcode = Application_Model_StoreItem::createBarcode();
        $item->Image = $this->_image;
        $item->ItemType = $this->_itemType;
        $item->Remark = $this->_remark;
        $item->Intype = $this->_intype;
        $item->OperateName = $this->_operateName;
        $item->Interior = Application_Model_StoreItem::Interior_InStored;
        $item->Isdelete = $this->_isdelete;
        $item->IsProblem = $this->_isProblem;
        $item->LocationNo = "LW-11";
        $item->save();
        return $item->Id;
    }
}

